const { Configuration, OpenAIApi } = require('openai')
const inquirer = require('inquirer')

const configuration = new Configuration({
  apiKey: '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',
})
const openai = new OpenAIApi(configuration)

async function getCompletion(prompt) {
  try {
    const res = await openai.createCompletion(
      {
        model: 'text-davinci-003',
        prompt: prompt,
        max_tokens: 5000,
        temperature: 0,
        stream: true,
      },
      { responseType: 'stream' }
    )

    res.data.on('data', (data) => {
      console.log(data)
      const lines = data
        .toString()
        .split('\n')
        .filter((line) => line.trim() !== '')
      for (const line of lines) {
        const message = line.replace(/^data: /, '')
        if (message === '[DONE]') {
          return // Stream finished
        }
        try {
          const parsed = JSON.parse(message)
          console.log(parsed.choices[0].text)
        } catch (error) {
          console.error('Could not JSON parse stream message', message, error)
        }
      }
    })
  } catch (error) {
    console.log(error)
    if (error.response.status) {
      console.error(error.response.status, error.message)
      error.response.data.on('data', (data) => {
        const message = data.toString()
        try {
          const parsed = JSON.parse(message)
          console.error('An error occurred during OpenAI request: ', parsed)
        } catch (error) {
          console.error('An error occurred during OpenAI request: ', message)
        }
      })
    } else {
      console.error('An error occurred during OpenAI request', error)
    }
  }
}

const prompt = inquirer.createPromptModule()

function main() {
  prompt([
    {
      type: 'input',
      message: 'Q:',
      name: 'question',
    },
  ])
    .then((answers) => {
      if (!answers.question) {
        console.log('question is empty!')
        main()
        return
      }

      return getCompletion(answers.question).then((answer) => {
        console.log(answer, '\n')
        main()
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

main()
